package com.jl.registermvc;

import com.jl.annotation.JLMvcApp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 这个是第二步
 * 通过注解启动了第一个步骤后，执行添加到容器中
 *
 * @author kelvin
 */
@Slf4j
public class ContractAutoHandlerRegisterConfiguration implements ImportBeanDefinitionRegistrar {


    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        log.info("开始注册-动态MVC创建规则");
        Map<String, Object> defaultAttrs = metadata
                .getAnnotationAttributes(JLMvcApp.class.getName(), true);
        //获取扫描包路径
        Set<String> basePackages = getBasePackages(metadata);
        //生成BeanDefinition并注册到容器中
        BeanDefinitionBuilder mappingBuilder = BeanDefinitionBuilder
                .genericBeanDefinition(ContractAutoHandlerRegisterHandlerMapping.class);
        mappingBuilder.addConstructorArgValue(basePackages);
        try {
            Class<?> forName = Class.forName("com.jl.config.ConciseMvcRegisterConfig");
            if (forName != null) {
                mappingBuilder.addDependsOn("conciseMvcRegisterConfig");
            }
        } catch (ClassNotFoundException e) {
            log.error(e.getMessage(), e);
        }
        registry.registerBeanDefinition("contractAutoHandlerRegisterHandlerMapping", mappingBuilder.getBeanDefinition());

        BeanDefinitionBuilder processBuilder = BeanDefinitionBuilder.genericBeanDefinition(ContractReturnValueWebMvcConfigurer.class);
        registry.registerBeanDefinition("contractReturnValueWebMvcConfigurer", processBuilder.getBeanDefinition());
        log.info("结束注册-动态MVC创建规则");

    }

    protected Set<String> getBasePackages(AnnotationMetadata importingClassMetadata) {
        Map<String, Object> attributes = importingClassMetadata
                .getAnnotationAttributes(JLMvcApp.class.getCanonicalName());

        Set<String> basePackages = new HashSet<>();
        for (String pkg : (String[]) attributes.get("basePackages")) {
            if (StringUtils.hasText(pkg)) {
                basePackages.add(pkg);
            }
        }
        //获取@JLMvcApp所在类的包
        /*if (basePackages.isEmpty()) {
            basePackages.add(
                    ClassUtils.getPackageName(importingClassMetadata.getClassName()));
        }*/
        return basePackages;
    }


}
